package threadcommunication;

/**
 * 使用等待通知机制实现多个线程间的通讯
 */
public class Demo_02 {
    public static void main(String[] args) {
        try {
            Object lock = new Object();
            MyList list = new MyList();
            Thread_01 t1 = new Thread_01(lock, list);
            t1.start();
            Thread.sleep(50);
            Thread_02 t2 = new Thread_02(lock, list);
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


class Thread_01 extends Thread {
    private Object lock;
    private MyList list;

    public Thread_01(Object lock, MyList list) {
        this.lock = lock;
        this.list = list;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {
                if(list.size() != 5) {
                    System.out.println("wait begin " + System.currentTimeMillis());
                    lock.wait();
                    System.out.println("wait end " + System.currentTimeMillis());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread_02 extends Thread {
    private Object lock;
    private MyList list;

    public Thread_02(Object lock, MyList list) {
        this.lock = lock;
        this.list = list;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {
                for(int i = 0; i < 10; i++) {
                    System.out.println("添加了" + (i + 1) + "个元素");
                    list.add();
                    if(list.size() == 5) {
                        lock.notify(); // 通知之后并不会立即释放所
                        System.out.println("已发出通知");
                        throw new InterruptedException();
                    }

                    Thread.sleep(1000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

